package com.gitee.kenewstar.utils.excel;

import com.gitee.kenewstar.exception.CommonException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;

import java.lang.reflect.Field;

/**
 * @author kenewstar
 * @date 2021/7/10
 */
public class TypeConverter {
	/**
	 * <p>
	 *     将excel单元格中的数据cell转换为Java中对应的数据类型
	 * </p>
	 * @param field 对象的属性
	 * @param cell excel的单元格
	 * @return 转换后的Java数据类型对象
	 */
	public static Object dataTypeConvert(Field field, Cell cell) {
		Class<?> type = field.getType();
		String typeName = type.getName();
		switch (typeName) {
			case "java.lang.String" :
				return cell.getStringCellValue();
			case "java.lang.Byte" :
			case "byte" :
				return (byte) cell.getNumericCellValue();
			case "java.lang.Short" :
			case "short" :
				return (short) cell.getNumericCellValue();
			case "java.lang.Integer" :
			case "int" :
				return (int) cell.getNumericCellValue();
			case "java.lang.Long" :
			case "long" :
				return (long) cell.getNumericCellValue();
			case "java.lang.Float" :
			case "float" :
				return (float) cell.getNumericCellValue();
			case "java.lang.Double" :
			case "double" :
				return cell.getNumericCellValue();
			case "java.lang.Boolean" :
			case "boolean" :
				return cell.getBooleanCellValue();
			case "java.util.Date" :
				return DateUtil.getJavaDate(cell.getNumericCellValue());
			default :
				throw new CommonException("data type error");
		}

	}
}
